<script setup>
import { storeToRefs } from "pinia";

import { useCityList } from "@/stores/cityList";

import { useRouter } from "vue-router";
import { onMounted, ref } from "vue";

//导入天气数据api
import { getWeatherByAdcode } from "@/apis";

// pinia store
const cityListmanager = useCityList();

const { cityList } = storeToRefs(cityListmanager);

const { removeCity } = cityListmanager;

//最终渲染的请求实时温度后的数据
const resList = ref([]);

const loading = ref(true);

// 跳转到城市详情页面
const router = useRouter();
const handleCityDetail = (adcode, cityName) => {
  router.push({ name: "info", query: { adcode, cityName } });
};

//处理温度数据
onMounted(async () => {
  if (cityList.value.length === 0) {
    return;
  }
  for (let city of cityList.value) {
    const { lives } = await getWeatherByAdcode(city.adcode, "base");
    resList.value.push({ ...city, temperature: lives[0].temperature });
  }
});

const handleRemoveCity = (id) => {
  removeCity(id);
  resList.value = resList.value.filter((city) => city.id!== id);
};
</script>

<template>
  <div
    class="citys-list mt-10 max-h-[300px]"
  >
    <template v-if="loading">
      <div
        v-for="city in resList"
        :key="city.id"
        class="item flex justify-between group"
      >
        <div
          class="bg-weather-second mb-4 py-2 px-4 flex justify-between cursor-pointer w-full duration-300 group-hover:w-4/5"
        >
          <h3>{{ city.cityName }}</h3>
          <span>{{ city.temperature }}度</span>
        </div>
        <!-- 默认隐藏按钮 -->
        <div class="mb-4 gap-2 hidden group-hover:flex">
          <button
            class="bg-yellow-500 text-center w-[80px]"
            @click="handleCityDetail(city.adcode, city.cityName)"
          >
            查看
          </button>
          <button
            class="bg-yellow-500 text-center w-[80px]"
            @click="handleRemoveCity(city.id)"
          >
            删除
          </button>
        </div>
      </div>
    </template>
    <p v-else class="text-center">天气信息加载中...</p>
  </div>
  <h2 class="text-center duration-200" v-if="cityList.length === 0">
    暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
  </h2>
</template>